import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { errorResponse, successResponse, optionsResponse } from '@/lib/response';
import { prisma } from '@/lib/prisma';
import { uploadFile } from '@/lib/storage';
import { authenticateRequest } from '@/utils/auth';
import { randomUUID } from 'crypto';

async function handler(req: NextRequest) {

  // 接受 JSON 或 FormData
  let svg: string | undefined;
  let filename: string | undefined;

  const contentType = req.headers.get('content-type') || '';
  try {
    if (contentType.includes('application/json')) {
      const body = await req.json();
      svg = body?.svg;
      filename = body?.filename;
    } else if (contentType.includes('multipart/form-data')) {
      const form = await req.formData();
      svg = form.get('svg') as string | null || undefined;
      filename = (form.get('filename') as string | null) || undefined;
    } else {
      // 其他类型按文本读取
      svg = await req.text();
    }
  } catch (e) {
    return errorResponse('请求体解析失败', 400);
  }

  if (!svg || typeof svg !== 'string' || svg.length === 0) {
    return errorResponse('缺少有效的svg字符串', 400);
  }

  // 生成文件名与对象键
  const baseNameRaw = (typeof filename === 'string' && filename.trim().length > 0)
    ? filename.trim().replace(/\s+/g, '_')
    : `svg_${randomUUID()}.svg`;
  const safeName = baseNameRaw.toLowerCase().endsWith('.svg') ? baseNameRaw : `${baseNameRaw}.svg`;
  const objectKey = `${randomUUID()}_${safeName}`;

  // 上传到 MinIO（放到 svg/ 目录）
  const buffer = Buffer.from(svg, 'utf-8');
  const stored = await uploadFile(buffer, objectKey, 'svg/');

  // 创建文件记录
  const record = await prisma.file.create({
    data: {
      userId: 'cmgxfef8j0000pfgs6j9a0kff',
      provider: 'minio',
      bucket: process.env.MINIO_BUCKET_NAME || 'kason-world',
      path: stored.path,
      url: stored.url,
      mimeType: stored.mimeType || 'image/svg+xml',
      size: stored.size,
      visibility: 'public',
      category: 'svg',
      source: 'system-upload-svg',
      status: 'active'
    }
  });

  return successResponse({ fileId: record.id, url: record.url, path: record.path });
}

export const POST = withMiddleware(handler);
export async function OPTIONS() {
  return optionsResponse();
}